//------------------------------------------------------------------------------
#include "localserver.h"
//------------------------------------------------------------------------------
LocalServer::LocalServer(const QString &serverName/*=DEFAULT_SERVER_NAME*/, QObject *parent/*=0*/) : QObject(parent){
	m_serverName = serverName;
	m_server = new QLocalServer(this);

	connect(m_server, SIGNAL(newConnection()), this, SLOT(newConnection_received()));
}
//------------------------------------------------------------------------------
LocalServer::~LocalServer(){
	// Cleaning still opened client connections
	foreach(ClientConnection *cc, m_clientConnections){
		Q_ASSERT(cc);
		cc->close();
		delete cc;
	}
	m_clientConnections.clear();

	m_server->close();
	delete m_server;
}
//------------------------------------------------------------------------------
bool LocalServer::start(){
	bool listenRet = m_server->listen(m_serverName);

	if(!listenRet)
		qWarning()<<"Error listening : "<<m_server->errorString();
	else
		qDebug()<<"Listening on : "<<m_server->fullServerName();

	return listenRet;
}
//------------------------------------------------------------------------------
void LocalServer::stop(){
	m_server->close();
}
//------------------------------------------------------------------------------
void LocalServer::newConnection_received(){
	QLocalSocket *clientSocket;

	// Manages incoming connections
	while((clientSocket = m_server->nextPendingConnection())){
		ClientConnection *cc = new ClientConnection(clientSocket, this);
		m_clientConnections.insert(cc);
		connect(cc, SIGNAL(disconnected()), this, SLOT(client_disconnected()));
		connect(cc, SIGNAL(messageReceived(STNMessage)), this, SIGNAL(messageReceived(STNMessage)));
	}
}
//------------------------------------------------------------------------------
void LocalServer::client_disconnected(){
	// Disconnected client
	ClientConnection *cc = (ClientConnection *)QObject::sender();

	Q_ASSERT(cc && m_clientConnections.contains(cc));

	m_clientConnections.remove(cc);
	delete cc;
}
//------------------------------------------------------------------------------
